/**
 * 表格通用逻辑组合式函数
 */
import { ref, reactive } from 'vue'
import type { PageParams, PageData } from '@/api/types'

/**
 * 表格Hook
 * @param fetchApi 获取数据的API函数
 * @param params 额外的查询参数
 */
export function useTable<T = any>(
  fetchApi: (params: any) => Promise<any>,
  params: Record<string, any> = {}
) {
  // 加载状态
  const loading = ref(false)

  // 表格数据
  const tableData = ref<T[]>([])

  // 分页参数
  const pagination = reactive<PageParams & { total: number }>({
    page: 1,
    pageSize: 10,
    total: 0
  })

  // 查询参数
  const queryParams = reactive({ ...params })

  /**
   * 获取表格数据
   */
  const fetchData = async () => {
    try {
      loading.value = true

      const requestParams = {
        ...queryParams,
        page: pagination.page,
        pageSize: pagination.pageSize
      }

      const { data } = await fetchApi(requestParams)

      const pageData = data as PageData<T>
      tableData.value = pageData.list
      pagination.total = pageData.total
    } catch (error) {
      console.error('fetchData error:', error)
      tableData.value = []
      pagination.total = 0
    } finally {
      loading.value = false
    }
  }

  /**
   * 搜索
   */
  const handleSearch = () => {
    pagination.page = 1
    fetchData()
  }

  /**
   * 重置
   */
  const handleReset = () => {
    Object.keys(queryParams).forEach((key) => {
      queryParams[key] = undefined
    })
    pagination.page = 1
    fetchData()
  }

  /**
   * 页码改变
   */
  const handlePageChange = (page: number) => {
    pagination.page = page
    fetchData()
  }

  /**
   * 每页条数改变
   */
  const handleSizeChange = (size: number) => {
    pagination.pageSize = size
    pagination.page = 1
    fetchData()
  }

  /**
   * 刷新当前页
   */
  const refresh = () => {
    fetchData()
  }

  return {
    loading,
    tableData,
    pagination,
    queryParams,
    fetchData,
    handleSearch,
    handleReset,
    handlePageChange,
    handleSizeChange,
    refresh
  }
}
